{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# TF-IDF简单示例"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1. 定义数据和预处理"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'中乙', '中甲', '中超', '巴甲', '德甲', '意甲', '法甲', '西甲', '阿甲'}"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "docA = \"西甲|法甲|意甲|德甲|中超|中超\"\n",
    "docB = \"西甲|意甲|中超\"\n",
    "docC = \"阿甲|德甲|巴甲|中甲|中乙|中超\"\n",
    "\n",
    "# 分词\n",
    "bowA = docA.split(\"|\")\n",
    "bowB = docB.split(\"|\")\n",
    "bowC = docC.split(\"|\")\n",
    "#bowA\n",
    "\n",
    "# set是不重复集合\n",
    "# union并集\n",
    "wordSet = set(bowA).union(set(bowB)).union(set(bowC))\n",
    "wordSet"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2. 统计词的频数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>阿甲</th>\n",
       "      <th>西甲</th>\n",
       "      <th>中乙</th>\n",
       "      <th>德甲</th>\n",
       "      <th>意甲</th>\n",
       "      <th>法甲</th>\n",
       "      <th>中超</th>\n",
       "      <th>巴甲</th>\n",
       "      <th>中甲</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>2</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>2</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   阿甲  西甲  中乙  德甲  意甲  法甲  中超  巴甲  中甲\n",
       "0   0   1   0   1   1   1   2   0   0\n",
       "1   0   1   0   0   1   0   1   0   0\n",
       "2   1   0   1   1   0   0   1   1   1"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 创建了三个字典数据结构，key为单词，value默认为0\n",
    "wordCountA = dict.fromkeys(wordSet, 0)\n",
    "wordCountB = dict.fromkeys(wordSet, 0)\n",
    "wordCountC = dict.fromkeys(wordSet, 0)\n",
    "\n",
    "for word in bowA:\n",
    "    wordCountA[word] += 1\n",
    "for word in bowB:\n",
    "    wordCountB[word] += 1\n",
    "for word in bowC:\n",
    "    wordCountC[word] += 1\n",
    "    \n",
    "import pandas as pd\n",
    "pd.DataFrame([wordCountA, wordCountB, wordCountC])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3. 计算词频"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "({'阿甲': 0.0,\n",
       "  '西甲': 0.16666666666666666,\n",
       "  '中乙': 0.0,\n",
       "  '德甲': 0.16666666666666666,\n",
       "  '意甲': 0.16666666666666666,\n",
       "  '法甲': 0.16666666666666666,\n",
       "  '中超': 0.3333333333333333,\n",
       "  '巴甲': 0.0,\n",
       "  '中甲': 0.0},\n",
       " {'阿甲': 0.0,\n",
       "  '西甲': 0.3333333333333333,\n",
       "  '中乙': 0.0,\n",
       "  '德甲': 0.0,\n",
       "  '意甲': 0.3333333333333333,\n",
       "  '法甲': 0.0,\n",
       "  '中超': 0.3333333333333333,\n",
       "  '巴甲': 0.0,\n",
       "  '中甲': 0.0},\n",
       " {'阿甲': 0.16666666666666666,\n",
       "  '西甲': 0.0,\n",
       "  '中乙': 0.16666666666666666,\n",
       "  '德甲': 0.16666666666666666,\n",
       "  '意甲': 0.0,\n",
       "  '法甲': 0.0,\n",
       "  '中超': 0.16666666666666666,\n",
       "  '巴甲': 0.16666666666666666,\n",
       "  '中甲': 0.16666666666666666})"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 在每个文档里的词频计算\n",
    "def computeTF(wordCount, bow):\n",
    "    # 记录tf结果\n",
    "    tfDict = {}\n",
    "    # 文档中一共有多少单词\n",
    "    bowCount = len(bow)\n",
    "    # 按照k：v进行遍历\n",
    "    for word, count in wordCount.items():\n",
    "        # 计算word的词频\n",
    "        tfDict[word] = count/float(bowCount)\n",
    "    return tfDict\n",
    "\n",
    "tfA = computeTF(wordCountA, bowA)\n",
    "tfB = computeTF(wordCountB, bowB)\n",
    "tfC = computeTF(wordCountC, bowC)\n",
    "tfA, tfB, tfC"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 4. 计算逆文档频率"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "idfDict:  {'阿甲': 0, '西甲': 0, '中乙': 0, '德甲': 0, '意甲': 0, '法甲': 0, '中超': 0, '巴甲': 0, '中甲': 0}\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'阿甲': 0.3010299956639812,\n",
       " '西甲': 0.12493873660829993,\n",
       " '中乙': 0.3010299956639812,\n",
       " '德甲': 0.12493873660829993,\n",
       " '意甲': 0.12493873660829993,\n",
       " '法甲': 0.3010299956639812,\n",
       " '中超': 0.0,\n",
       " '巴甲': 0.3010299956639812,\n",
       " '中甲': 0.3010299956639812}"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 统一传入所有文档的wordCount字典\n",
    "def computeIDF(docList):\n",
    "    # 导入math库\n",
    "    import math\n",
    "    # 初始化一个空字典\n",
    "    idfDict = {}\n",
    "    # N为字典key的数量\n",
    "    N = len(docList)\n",
    "    \n",
    "    idfDict = dict.fromkeys(docList[0].keys(), 0)\n",
    "    print('idfDict: ', idfDict)\n",
    "    \n",
    "    for doc in docList:\n",
    "        # 遍历doc的k v键值对\n",
    "        for word, count in doc.items():\n",
    "            if count > 0:\n",
    "                idfDict[word] += 1\n",
    "    for word, count in idfDict.items():\n",
    "        idfDict[word] = math.log10( (N+1)/float(count + 1) )\n",
    "    return idfDict\n",
    "\n",
    "idfs = computeIDF([wordCountA, wordCountB, wordCountC])\n",
    "idfs"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 5. 计算TF-IDF"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>阿甲</th>\n",
       "      <th>西甲</th>\n",
       "      <th>中乙</th>\n",
       "      <th>德甲</th>\n",
       "      <th>意甲</th>\n",
       "      <th>法甲</th>\n",
       "      <th>中超</th>\n",
       "      <th>巴甲</th>\n",
       "      <th>中甲</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <td>0</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>0.020823</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>0.020823</td>\n",
       "      <td>0.020823</td>\n",
       "      <td>0.050172</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>0.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>1</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>0.041646</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>0.041646</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>0.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>2</td>\n",
       "      <td>0.050172</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>0.050172</td>\n",
       "      <td>0.020823</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.050172</td>\n",
       "      <td>0.050172</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "         阿甲        西甲        中乙        德甲        意甲        法甲   中超        巴甲  \\\n",
       "0  0.000000  0.020823  0.000000  0.020823  0.020823  0.050172  0.0  0.000000   \n",
       "1  0.000000  0.041646  0.000000  0.000000  0.041646  0.000000  0.0  0.000000   \n",
       "2  0.050172  0.000000  0.050172  0.020823  0.000000  0.000000  0.0  0.050172   \n",
       "\n",
       "         中甲  \n",
       "0  0.000000  \n",
       "1  0.000000  \n",
       "2  0.050172  "
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def computeTFIDF(tf, idfs):\n",
    "    tfidf = {}\n",
    "    for word, tf in tf.items():\n",
    "        tfidf[word] = tf * idfs[word]\n",
    "    return tfidf\n",
    "\n",
    "tfidfA = computeTFIDF(tfA, idfs)\n",
    "tfidfB = computeTFIDF(tfB, idfs)\n",
    "tfidfC = computeTFIDF(tfC, idfs)\n",
    "pd.DataFrame([tfidfA, tfidfB, tfidfC])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
